<template>
	<Modal :mask-closable="false" v-model="deviceVisible" width="1200" title="新建" class="modal-content-layout other">
		<!-- {{ formTop }} -->
		<Form ref="deviceForm" :model="formTop" label-position="top" :rules="validateDevice">
			<div class="item">
				<Row :gutter="16">
					<Col :span="8">
						<FormItem label="工单号" prop="workCode">
							<Select
								v-model="formTop.workCode"
								filterable
								clearable
								placeholder="请输入工单号"
								:remote-method="handleRemote"
								:loading="searchLoading"
								@on-select="handleChange"
							>
								<Option v-for="(item, i) in workOrderList" :value="item.workCode" :label="item.workCode" :key="i"> </Option>
							</Select>
						</FormItem>
					</Col>
					<Col :span="8">
						<FormItem label="班次时间" prop="shiftTime">
							<DatePicker
								style="width: 100%"
								@on-change="shiftTimeChange"
								:value="formTop.shiftTime"
								type="date"
								placeholder="请选择班次时间"
							></DatePicker>
						</FormItem>
					</Col>
					<Col :span="8">
						<FormItem label="班次" prop="shiftId">
							<Select v-model="formTop.shiftId" placeholder="请选择班次" @on-select="shiftChange">
								<Option v-for="(item, i) in shiftList" :value="item.id" :label="item.shift" :key="i"> </Option>
							</Select>
						</FormItem>
					</Col>
				</Row>
				<!-- <Row :gutter="16">
          <Col :span="8">
            <FormItem label="投料类型" prop="feedingStatus">
              <Select v-model="formTop.feedingStatus" placeholder="请选择">
                <Option label="投料" value="投料"></Option>
                <Option label="退料" value="退料"></Option>
              </Select>
            </FormItem>
          </Col>
        </Row> -->
			</div>
			<!-- {{ social }} -->
			<CheckboxGroup v-model="social" v-if="addList.length > 0">
				<div class="mt16 item" v-for="(item, index) in addList" :key="index">
					<Checkbox :label="item">序号{{ index + 1 }}</Checkbox>
					<Row :gutter="16">
						<Col :span="8">
							<FormItem label="物料编号">
								<Input :value="item.materialCode" readonly />
							</FormItem>
						</Col>
						<Col :span="8">
							<FormItem label="物料名称" prop="materialName">
								<Input :value="item.materialName" readonly />
							</FormItem>
						</Col>
						<Col :span="8">
							<FormItem label="规格型号" prop="materialModel">
								<Input :value="item.materialModel" readonly />
							</FormItem>
						</Col>
					</Row>
					<Row :gutter="16">
						<Col :span="8">
							<FormItem label="材料牌号">
								<Input :value="item.materialMark" readonly />
							</FormItem>
						</Col>
						<Col :span="8">
							<FormItem label="数量" prop="weight" require>
								<InputNumber
									:precision="3"
									:active-change="false"
									:step="1"
									style="width: 100%"
									:max="9999999"
									:parser="(val) => util.numberFormatNoFixed(val, 3)"
									v-model="item.weight"
								/>
							</FormItem>
						</Col>
						<Col :span="8">
							<FormItem label="单位" require>
								<Input v-model="item.unit" readonly />
							</FormItem>
						</Col>
					</Row>
				</div>
			</CheckboxGroup>
		</Form>
		<div slot="footer">
			<Button type="default" @click="deviceVisible = false">{{ $t('common.Cancle') }}</Button>
			<Button type="primary" :loading="loadingVisible" @click="submit">{{ $t('maintenance.Confirmed') }}</Button>
		</div>
		<commonModal ref="commonModal"></commonModal>
	</Modal>
</template>

<script>
import moment from 'moment';
import commonModal from '@/components/modalTypes/commonModal.vue';

export default {
	name: 'addModal',
	components: { commonModal },
	data() {
		return {
			social: [],
			deviceVisible: false,
			loadingVisible: false,
			searchLoading: false,
			formTop: {
				shiftTime: '',
			},
			shiftList: [],
			validateDevice: {
				workCode: [
					{
						required: true,
						message: `${this.$t('common.inputInfo')}`,
						trigger: 'change',
					},
				],
				shiftTime: [
					{
						required: true,
						message: `${this.$t('common.inputInfo')}`,
						trigger: 'change',
					},
				],
				shift: [
					{
						required: true,
						message: `${this.$t('common.inputInfo')}`,
						trigger: 'change',
					},
				],
			},
			workOrderList: [
				// {
				//   workCode: "1100005867001",
				// },
			],
			workInfo: {},
			addList: [],
			wareHouseList: {},
			wareHouseList2: [],
		};
	},
	mounted() {
		// this.getWareHouse2()
	},
	methods: {
		reset() {
			this.$set(this, 'social', []);
			this.$set(this, 'addList', []);
		},
		getWareHouse() {
			this.axios({
				url: '/dms/mobileEnd/getUseWarehouse',
				method: 'get',
				params: {
					deviceNo: this.workInfo.deviceCode,
				},
			}).then((res) => {
				this.wareHouseList = res.data || {};
			});
		},
		// getWareHouse2() {
		//   this.axios({
		//     url: "/dms/materialOperation/queryWarehouse",
		//     method: "get",
		//   }).then((res) => {
		//     this.wareHouseList2 = res.data || [];
		//   });
		// },
		handleChange(val) {
			this.axios({
				url: '/dms/mobile/selectWorkByWorkCode',
				method: 'get',
				params: {
					workCode: val.value,
				},
			}).then((res) => {
				this.workInfo = res.data || {};
				this.getWareHouse();
				if (this.formTop.shiftTime) {
					this.shiftTimeChange(this.formTop.shiftTime);
				}
			});
		},
		shiftTimeChange(val) {
			this.shiftList = [];
			this.formTop.shiftId = null;
			this.reset();
			if (val) {
				this.formTop.shiftTime = val;
				this.getShiftList(val);
			}
		},
		getShiftList(shiftTime) {
			this.shiftList = [];
			this.formTop.shiftId = null;
			this.formTop.shift = null;
			this.axios({
				url: '/dms/mobile/getShiftList',
				method: 'get',
				params: {
					shiftDate: shiftTime ? moment(shiftTime).format('YYYY-MM-DD') : '',
					deviceNo: this.workInfo.deviceCode,
				},
			}).then((res) => {
				this.shiftList = res.data;
				this.formTop.shift = res.data[0].shift;
				this.formTop.shiftId = res.data[0].id;
				this.getAddList();
			});
		},
		shiftChange(obj) {
			this.formTop.shift = obj.label;
			this.formTop.shiftId = obj.value;
			this.getAddList();
		},
		getAddList() {
			if (!this.formTop.workCode && !this.formTop.shiftId) {
				this.$Message.warning('请先选择工单和班次');
				return;
			}
			this.axios({
				url: '/dms/mobileEnd/getMaterialAddList',
				method: 'get',
				params: {
					pageSize: 50,
					pageNum: 1,
					workCode: this.formTop.workCode,
					shiftId: this.formTop.shiftId,
				},
			}).then((res) => {
				this.addList = res.data.records.map((item) => {
					return {
						...item,
						weight: 1,
					};
				});
			});
		},
		show() {
			this.$refs.deviceForm.resetFields();
			this.reset();
			this.workOrderList = [];
			this.deviceVisible = true;
			this.formTop = {
				shiftTime: '', // moment().format('YYYY-MM-DD')
				shiftId: null,
				shift: null,
			};
		},
		submit() {
			this.$refs.deviceForm.validate((valid) => {
				if (valid) {
					if (this.social.length === 0){
						this.$Message.warning('请选择一条数据');
						return;
					} 
					let result = true;
					for (let index = 0; index < this.social.length; index++) {
						const element = this.social[index];
						if (!element.weight) {
							result = false;
						}
					}
					if (!result) {
						this.$Message.warning('选择数据的数量不能为空或者是0');
						return;
					}
					const paramList = this.social.map((item) => {
						return {
							materialCode: item.materialCode,
							workCode: this.formTop.workCode,
							shiftId: this.formTop.shiftId,
							shift: this.formTop.shift,
							shiftTime: this.formTop.shiftTime,
							quantity: item.weight,
							unit: item.unit,
						};
					});
					const checkData = paramList.map((item) => {
						return {
							workCode: item.workCode,
							materialCode: item.materialCode,
							batchNumber: item.materialBatch || '',
						};
					});
					const that = this;
					that
						.axios({
							url: '/dms/materialOperation/queryMaterialLimitation',
							data: checkData,
							method: 'post',
						})
						.then((res) => {
							if (res.data.includes(1)) return this.$Message.error('禁止挪用投料');
							else {
								that.$refs.commonModal.showModal({
									title: '确认',
									type: 'sure',
									desc: res.data.includes(2) ? '该投料订单与当前生产订单无关' : '确认提交吗',
									submit: () => {
										that.addAxios(paramList);
									},
								});
							}
						});
				}
			});
		},
		addAxios(paramList) {
			this.axios({
				url: '/dms/materialHeadTail/saveMaterialHeadTail',
				data: paramList,
				method: 'post',
			}).then((res) => {
				if (res.code == 200) {
					this.$Message.success('操作成功');
					this.deviceVisible = false;
					this.$emit('refresh');
				} else {
					this.$Message.error(res.msg);
				}
			});
		},
		handleRemote(query) {
			if (query !== '') {
				this.searchLoading = true;
				let _query = query.split('-');
				if (Array.isArray(_query)) _query = _query[0];
				this.axios({
					method: 'post',
					url: '/dms/productionWork/queryWorkList',
					data: {
						pageSize: 50,
						pageNum: 1,
						workCode: _query,
					},
				})
					.then((res) => {
						if (res.code === 200) {
							this.workOrderList = res.data.records;
						} else {
							this.$Message.warning({
								content: res.msg,
								duration: 6,
								closable: true,
							});
						}
					})
					.finally(() => {
						this.searchLoading = false;
					});
			} else {
				this.workOrderList = [];
			}
		},
	},
};
</script>

<style lang="scss" scoped>
/deep/ .ivu-modal-body {
	background: transparent !important;
	padding: 0 !important;
	box-shadow: none;
}

.item {
	background: #fff;
	border-radius: 8px;
	padding: 16px;
	box-shadow: 0px 4px 8px 0px rgba(0, 20, 45, 0.04);
}

.demo-upload-list {
	position: relative;
	width: 60px;
	height: 60px;
	text-align: center;
	line-height: 60px;
	border-radius: 4px;
	background: #fff;
	box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
	margin-left: 15px;

	img {
		width: 100%;
		height: 100%;
	}

	.delIcon {
		position: absolute;
		right: -10px;
		top: -10px;
		color: red;
		font-size: 20px;
		background: #fff;
		border-radius: 50%;
		cursor: pointer;
	}
}
</style>
